package com.lily.aidouzixun.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.lily.aidouzixun.MyApplication;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.HardWare;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConfig;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.ProgressDialogUtil;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.util.Validator;

import java.lang.ref.WeakReference;

/**
 * 注册
 */
public class RegisterActivity extends Activity {
    private static final String TAG = "RegisterActivity";

    private TitleBar mTitleBar;
    private EditText etUsername;
    private EditText etPassword;
    private Button bnRegister; //注册按钮
    private static ProgressDialog mProgressDialog; //网络请求时用的进度条

    private String key = "";
    private Activity mActivity;
    private static Context mContext;
    private String backTitle;   //返回标题
    private static final String TITLE = "注册";
    private MyHandler myHandler;

    private static String urid;    //用户编号
    private static String username;    //用户名
    private static String password;    //密码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        init();
        findViews();
        setListeners();
    }

    /**
     * 初始化
     */
    private void init() {
        this.key += this.hashCode();
        mActivity = RegisterActivity.this;
        mContext = RegisterActivity.this;
        //得到返回标题
        Intent intent = getIntent();
        backTitle = intent.getStringExtra(MyConstant.IntentKey.BACK_TITLE);
        myHandler = new MyHandler(mActivity);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
    }

    /**
     * 找到控件
     */
    private void findViews() {
        //标题栏
        mTitleBar = (TitleBar) findViewById(R.id.mytitlebar);
        mTitleBar.setTitle(TITLE);
        mTitleBar.setLeftOperation(backTitle);
        mTitleBar.setCurActivity(mActivity);
        //登录
        etUsername = (EditText) findViewById(R.id.et_username);
        etPassword = (EditText) findViewById(R.id.et_password);
        bnRegister = (Button) findViewById(R.id.bn_register);
    }

    private void setListeners() {
        //注册
        bnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                username = etUsername.getText().toString().trim();
                password = etPassword.getText().toString().trim();
                if (!Validator.isEffective(username)) {
                    T.longToast(mContext, "用户名不能为空！");
                    return;
                }
                if (Validator.isNumber(username)) {
                    T.longToast(mContext, "用户名不能为纯数字！");
                    return;
                }
                if (Validator.isNumber(username)) {
                    T.longToast(mContext, "用户名不能为纯数字！");
                    return;
                }
                if (!Validator.isUserNameLength(username)) {
                    T.longToast(mContext, "用户名在4-18位之间！");
                    return;
                }
                if (!Validator.isEffective(password)) {
                    T.longToast(mContext, "密码不能为空！");
                    return;
                }
                if (Validator.isNumber(password)) {
                    T.longToast(mContext, "密码不能为纯数字！");
                    return;
                }
                if (!Validator.isPasswLength(password)) {
                    T.longToast(mContext, "密码在6-18位之间！");
                    return;
                }
                //用户注册
                userRegister(username, password);
            }
        });
    }

    /**
     * 用户注册
     * @param username 用户名
     * @param password 密码
     */
    private void userRegister(String username, String password) {
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.USER_REGISTER);
        param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.USER_REGISTER);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, myHandler);
        param.put(MyConstant.RequireParams.USER_NAME, username);
        param.put(MyConstant.RequireParams.PASSWORD, password);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 注册成功以后的处理
     */
    private void registerSuccess() {
        if (Validator.isEffective(urid)) {  //设置用户id
            MyConfig.setUserId(mContext, urid);
        }
        //把注册的用户名和密码传递到登录页面
        Intent intent = new Intent();
        intent.putExtra(MyConstant.IntentKey.USER_NAME, username);
        intent.putExtra(MyConstant.IntentKey.PASSWORD, password);
        mActivity.setResult(1, intent);
        mActivity.finish();
    }

    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        /**
         * 构造方法，传递Activity对象，防止内存泄露
         * @param mActivity
         */
        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final RegisterActivity activity = (RegisterActivity) mActivityReference.get();
                if(activity !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (msg.arg1 == MyConstant.DataType.USER_REGISTER) {
                                if (mProgressDialog != null) {
                                    mProgressDialog.setMessage("正在注册...");
                                    mProgressDialog.show();
                                }
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == MyConstant.DataType.USER_REGISTER) {
                                SparseArray<String> registerResult = (SparseArray<String>) msg.obj;
                                String errno = registerResult.get(0);
                                if ("0" .equals(errno) ) {  //注册成功
                                    urid = registerResult.get(2);
                                    //注册成功的处理
                                    activity.registerSuccess();
                                } else if ("1" .equals(errno)) { //用户已经注册
                                    T.longToast(mContext, registerResult.get(1));
                                }else { //注册失败
                                    T.longToast(mContext, "注册失败，请稍后再试...");
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }
}
